package com.gx.core
{
	import com.gx.interfaces.IDrawable;
	import com.gx.interfaces.IPhysical;
	import com.gx.interfaces.IPhysicsLayer;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.PixelSnapping;
	import flash.display.Sprite;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.geom.Rectangle;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	import flash.xml.XMLNode;
	

	public class Game extends Sprite
	{
		private var _drawableComponents:Array = new Array();
		private var _physicsComponents:Array = new Array();
		private var _physicsWorlds:Array = new Array();
		
		
		public var stepSize:Number = 1/60;
		public var iterations:int = 30;
		
		
		private var _timer:Timer;
		private var _ticksPerSec:int;
		private var _currTime:int;
		private var _accumulator:int;
		private var _tf:TextField;

		
		public function Game()
		{
		
		}
		
		private function stageAddedHandler(e:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, stageAddedHandler);
			init();
		}
		
		
		
		public function loadSceneXML(xmlLocation:String):void
		{
			var loader:URLLoader = new URLLoader();
			var request:URLRequest = new URLRequest(xmlLocation);
			loader.load(request);
			loader.addEventListener(Event.COMPLETE, onXMLLoaded);
		}
		
		private function onXMLLoaded(event:Event):void
		{
			var scene:Scene = parseSceneXML(new XML(URLLoader(event.target).data));
			this.scenes.push(scene);
		}
		
		public function parseSceneXML(sceneXML:XML):Scene
		{
			var scene:Scene = new Scene();
			scene.parseXML(sceneXML);
			
			return scene;
		}
		
		public function init():void
		{
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			_ticksPerSec = stepSize * 1000;
			_timer = new Timer(1000 / 120);
			start();
		}


		
		public function start():void
		{
			_accumulator = 0;
			_currTime = getTimer();
			_timer.addEventListener(TimerEvent.TIMER, timerHandler);
			_timer.start();


		}
		
		private function timerHandler(e:TimerEvent = null):void
		{
			var i:int, k:int;
			
			var newTime:int = getTimer();
			var deltaTime:int = newTime - _currTime;
			_currTime = newTime;
			
			if (deltaTime > 100) deltaTime = 100;
			
			_accumulator += deltaTime;
			while (_accumulator >= _ticksPerSec)
			{
				_accumulator -= _ticksPerSec;
				
				
				for each(var scene:Scene in _scenes)
				{
					scene.update(deltaTime);
				}
				
			}

		    
		}

		private var _scenes:Array = new Array();
		public function get scenes():Array {return _scenes;}
		public function set scenes(value:Array):void 
		{
			_scenes = value;
		}
		

		
	}
}